# syndication.py
# @author Africa iParliaments Action Plan
# 
# Provides Feed Data From Various Sources

from plonetheme.apkntheme.settings import ANM_NEWS_URL,\
                                          ANM_PARLIAMENT_FEEDS,\
                                          ANM_PARL_NEWS_URL,\
                                          ANM_PARL_FEED_URL,\
                                          DEFAULT_FEED_LANGUAGE

from plonetheme.apkntheme.settings import TWG_FEED_BASE_URL,\
                                          TWG_FEED_PORTAL_TYPES,\
                                          TWG_MENU,\
                                          TWG_PARAMETER_DEFAULT_VALUES,\
                                          TWG_ROOT,\
                                          TWG_SPACES_ROOT,\
                                          TWG_FEED_PARAMETERS,\
                                          TWG_FEED_PATH_ROOT

from plonetheme.apkntheme.utils import feedparser
from plonetheme.apkntheme import logger
from plone.memoize import ram
from time import time

from urllib import quote

def qt(v):
    return quote(v, safe="+")

import random
import string

DOM_ID_SUFFIX_LENGTH = 10
HOURS_TO_CACHE = 1

def _feed_items_cache_key(method, feed_url):
    return (feed_url, time()//(60 * HOURS_TO_CACHE))

#temporary value - this should be computed from request
def random_string():
    chars = string.ascii_lowercase
    random_indices = [random.randrange(0,len(chars)) for i in range(0, 
                        DOM_ID_SUFFIX_LENGTH)]
    return ''.join([chars[index] for index in random_indices])

@ram.cache(_feed_items_cache_key)
def getFeedItems(feed_url):
    feed_items = []
    try:
        feed = feedparser.parse(feed_url)
        logger.info("Processing feed at address %s", feed_url)
        feed_items = feed.entries
    except:
        logger.error("Failed to load feed at  address: %s", feed_url)
    return feed_items


def buildParliamentaryFeedInfo():
    '''
    This can be be better refactored but should work for now
    '''
    feed_data = list()
    for feed in ANM_PARLIAMENT_FEEDS:
        rss_url = ANM_PARL_FEED_URL %(feed['id'], 
        DEFAULT_FEED_LANGUAGE)
        feed_item = {}
        feed_item['title'] = feed['title']
        feed_item['news_url'] = ANM_PARL_NEWS_URL %(DEFAULT_FEED_LANGUAGE,
        feed['id'])
        feed_item['feed_url'] = rss_url
        feed_item['dom_element_id'] = random_string()
        feed_data.append(feed_item)
    return feed_data


def buildTWGFeedInfo(twg_feed_base_url):
    feed_data = []    
    for feed_type in TWG_FEED_PORTAL_TYPES:
        feed_title = feed_type['title']
        feed_section = {
                        'feeds': [],
                        'title': feed_title,
                        'id' : feed_type['id']
                        }
        if feed_type.get("feed_address"):
            feed_info = {}
            feed_url_final = feed_type.get('feed_address')
            feed_info['feed_url'] = feed_type.get('feed_address')
            feed_info['feed_items'] = getFeedItems(feed_url_final)
            feed_info['feed_title'] = feed_type.get('title')
            feed_section['feeds'].append(feed_info)
        else:
            for twg_item in TWG_MENU:
                feed_section_title = twg_item['title']
                feed_id = twg_item['id']
                feed_base_address = twg_item['address']
                feed_search_path = '/'.join((TWG_FEED_PATH_ROOT, 
                                            feed_base_address))
                feed_info = {}
                url_params = [qt(fp) + '=' + qt(feed_type['params'].get(fp, '')) 
                for fp in TWG_FEED_PARAMETERS]
                feed_url_base = '/'.join((
                                    twg_feed_base_url,
                                    TWG_SPACES_ROOT,
                                    TWG_FEED_BASE_URL))
                url_params.append("=".join((u"path", feed_search_path)))
                url_params_nmlz = '&'.join(url_params)
                feed_url_final = '?'.join((feed_url_base, url_params_nmlz))
                feed_info['feed_url'] = feed_url_final
                feed_info['feed_title'] = twg_item['title']
                feed_info['feed_items'] = getFeedItems(feed_url_final)
                feed_section['feeds'].append(feed_info)
        feed_data.append(feed_section)
    return feed_data
    
